package concurrecy.util;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

class CountDownTask implements Runnable {
    private CountDownLatch latch;
    private Random random = new Random();

    public CountDownTask(CountDownLatch latch) {
        this.latch = latch;
    }

    @Override
    public String toString() {
        return Thread.currentThread().getName();
    }

    @Override
    public void run() {
        try {
            TimeUnit.MILLISECONDS.sleep(random.nextInt(10000));
            latch.countDown();
            System.out.println(this + " task completed");
        } catch (InterruptedException e) {
            System.out.println(this + " interrupted");
        }
    }
}

public class CountDownLatchDemo {
    final static int SIZE = 10;
    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(SIZE);
        ExecutorService service = Executors.newCachedThreadPool();
        for (int i = 0; i < SIZE; i++) {
            service.execute(new CountDownTask(latch));
        }
        latch.await();
        System.out.println("all task is completed");
        service.shutdown();
    }
}
